package com.hyper_yang.javase.multiThread;

public class Thread_safe_lockMethod {
    public static void main(String[] args) {
//        WindowRunnable1 windowRunnable = new WindowRunnable1();
//        Thread w1 = new Thread(windowRunnable, "窗口1");
//        Thread w2 = new Thread(windowRunnable, "窗口2");
//        Thread w3 = new Thread(windowRunnable, "窗口3");
//
//        w1.start();
//        w2.start();
//        w3.start();

        WindowThread1 t1 = new WindowThread1("窗口1");
        WindowThread1 t2 = new WindowThread1("窗口2");
        WindowThread1 t3 = new WindowThread1("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class WindowRunnable1 implements Runnable {

    int tickets = 100;

    @Override
    public void run() {
        while (true) {
            if (tickets <= 0) {
                System.out.println("票卖完了！！！");
                break;
            }
            sellTickets();
        }
    }

    // 实例方法，synchronized的锁对象是当前类的对象 this
    public synchronized void sellTickets(){
        if (tickets <= 0) {
            return;
        }
        try {
            Thread.sleep(20); // 模拟出票过程
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        tickets--;
        System.out.println(Thread.currentThread().getName() + "卖了一张票，剩余" + tickets + "张票");
    }
}

class WindowThread1 extends Thread {
    static int tickets = 100;
    public WindowThread1(String name) {
        super(name);
    }
    @Override
    public void run() {
        while (true) {
            if (tickets <= 0) {
                System.out.println("票卖完了！！！");
                break;
            }
            this.sellTickets();
        }
    }

    // 同步静态方法: synchronized锁的是当前类对象(类加载时，类也会产生一个对象放在堆中)
    public static synchronized void sellTickets(){
        if (tickets <= 0) {
            return;
        }
        try {
            Thread.sleep(20); // 模拟出票过程
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        tickets--;
        System.out.println(Thread.currentThread().getName() + "卖了一张票，剩余" + tickets + "张票");
    }
}